import React, { useEffect } from 'react';
import { Form, Input, Select, Button, message, Radio } from 'antd';
import { connect } from 'react-redux'
import YzhTree from '@com/YzhTree'
import api from '@/api/apiList';
import { useCustomState } from '@/hooks/useEffect';
import { ValidationRules } from '@/utils'
import { storage } from '@/utils/storage'
import {
    hasPermission,
    hasRoles,
    permissionCodes as pCodes
} from '@/routes/permission'
const { Option } = Select
import config from '@/config'
const { setting } = config
const AddOrEditUser = (props) => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useCustomState(true)
    const [state, setState] = useCustomState({
        erpOptions: [],
        roleList: [],
        form: {
            account: undefined,
            id: undefined,
            name: undefined,
            phone: undefined,
            deptId: undefined,
            roleIds: undefined,
            saleErpCode: '',
            password: undefined,
            reptpassword: undefined,
        }
    })
    useEffect(() => {
        const initData = async () => {
            try {
                setLoading(true)
                let role = await api.userCenter.role.listAll()
                let res = await api.common.departmentCombobox({}, state.form.id ? pCodes.user.edit : pCodes.user.add)
                const { search } = props.location
                const paramsString = search.substring(1)
                const searchParams = new URLSearchParams(paramsString)
                const id = searchParams.get('id')
                if (id) {
                    let user = await api.userCenter.user.getUserInfo({ userId: id })
                    form.setFieldsValue({
                        ...user.result,
                        userLevel: user.result.userLevel.code,
                        reptpassword: user.result.reptpassword || undefined
                    })
                    setState({
                        ...state,
                        erpOptions: res.result,
                        roleList: role.result,
                        form: {
                            ...user.result,
                            reptpassword: user.result.reptpassword || undefined,
                        }
                    })
                    setLoading(false)
                    return
                }
                setState({
                    ...state,
                    erpOptions: res.result,
                    roleList: role.result
                })
                setLoading(false)
            } catch (error) {
                setLoading(false)
                console.log(error);
            }
        }
        initData()
    }, [props, form])
    const onFinish = () => {
        form
            .validateFields()
            .then(async (values) => {
                if (values.reptpassword !== values.password && !state.form.id) {
                    message.error('输入的两次密码不一致，请重新输入！')
                    return
                }
                let apiStr = 'add'
                if (state.form.id) {
                    apiStr = 'edit'
                    values.userId = state.form.id
                }
                setLoading(true)
                let res = await api.userCenter.user[apiStr]({ ...values, userSource: 1001 })
                await setLoading(false)
                if (res && res.success) {
                    res && res.success && message.success('操作成功')
                    if (storage.get('userInfo').userId &&
                        storage.get('userInfo').userId === values.userId) {
                        message.success(props.globalConfig.setting.message.user)
                        props.logout()
                        props.filterTabs('3')
                        return
                    }
                    // res && res.success && form.resetFields()
                    props.removeTabs('/userCenter/edit', true)
                    props.addTabs({
                        activeKey: '/userCenter/userManage',
                        title: '用户管理',
                        isCloseOpen: true
                    })
                    props.history.push('/userCenter/userManage')
                    // props.changeTabs({ activeKey: '/userCenter/userManage' })
                    // props.filterTabs('1')
                }
            })
            .catch((info) => {
                console.log('Validate Failed:', info);
            });
    }
    // 获取erp数据
    const getErpData = async () => {
        setLoading(true)
        let res = await api.common.departmentSync({}, state.form.id ? pCodes.user.edit : pCodes.user.add)
        res && res.success && message.success('操作成功')
        setLoading(false)
    }
    const { erpOptions, roleList } = state
    return <div className="yzh-user">
        <Form
            name="editUserForm"
            form={form}
            style={{
                padding: 30,
                maxWidth: 600
            }}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            initialValues={{ userLevel: 1001 }}
            onFinish={onFinish}
            autoComplete="off"
        >
            <Form.Item
                label="账号"
                name="account"
                rules={[
                    {
                        required: !state.form.id,
                        validator: (rule, value) => {
                            if (state.form.id) {
                                return Promise.resolve()
                            }
                            return new ValidationRules({
                                prop: 'account',
                                message: '账号',
                                type: 'account',
                                limit: 11,
                                inputControll: true,
                                value
                            }).validate(rule, value)
                        },
                    },
                ]}
            >
                <Input disabled={state.form.id} placeholder="请输入账号" key="account" maxLength={30} />
            </Form.Item>
            <Form.Item
                label="姓名"
                name="name"
                rules={[
                    {
                        required: true,
                        validator: (rule, value) => {
                            return new ValidationRules({
                                prop: 'account',
                                message: '姓名',
                                type: 'chinese',
                                value
                            }).validate(rule, value)
                        },
                    },
                ]}
            >
                <Input placeholder="请输入姓名" key="name" maxLength={5} />
            </Form.Item>
            <Form.Item
                label="电话"
                name="phone"
                rules={[
                    {
                        required: true,
                        validator: (rule, value) => {
                            return new ValidationRules({
                                prop: 'phone',
                                message: '电话',
                                type: 'phone',
                                limit: 11,
                                inputControll: true,
                                value
                            }).validate(rule, value)
                        },
                    },
                ]}
            >
                <Input placeholder="请输入电话" key="phone" />
            </Form.Item>
            <Form.Item
                label="部门"
                name="deptId"
                rules={[{ required: true, message: '请选择部门' }]}
            >
                {<YzhTree
                    key="deptId"
                    pcode={pCodes.user.list}
                    onSelect={(val) => {
                        form.setFieldsValue({ deptId: val })
                    }} value={state.form.deptId} select="true" />}
            </Form.Item>
            <Form.Item
                name="roleIds"
                label="角色"
                rules={[{ required: true, message: '请选择角色' }]}
            >
                <Select
                    key="roleIds"
                    showSearch
                    allowClear
                    placeholder="请选择角色"
                    mode="multiple"
                    disabled={state.form.id === 1}
                    value={state.form.roleIds || []}
                    optionFilterProp="label"
                    filterOption={(input, option) => {
                        return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    }>
                    {
                        roleList.map(el => {
                            return <Option key={el.id} value={el.id} label={el.name}>{el.name}</Option>
                        })
                    }
                </Select>
            </Form.Item>
            <Form.Item
                label="erp用户"
                rules={[{ required: false, message: '请选择erp用户' }]}
            >
                <Form.Item name="saleErpCode"
                    style={{ width: 310, float: 'left', marginBottom: 0 }}
                    rules={[{ required: false, message: '请选择erp用户' }]}
                >
                    <Select
                        showSearch
                        placeholder="请选择erp用户"
                        value={state.form.saleErpCode || ''}
                        optionFilterProp="label"
                        allowClear
                        filterOption={(input, option) => {
                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        }>
                        {
                            erpOptions.map(el => {
                                return <Option key={el.erpCode} value={el.erpCode} label={el.erpName}>{el.erpName}</Option>
                            })
                        }
                    </Select>
                </Form.Item>
                <Button onClick={getErpData} loading={loading} style={{ float: 'right' }} size={'mini'}>获取erp数据</Button>
            </Form.Item>
            <Form.Item
                name="userLevel"
                label="等级"
                rules={[
                    {
                        required: true,
                        message: '请选择等级!',
                    },
                ]}
            >
                <Radio.Group value={state.form.userLevel || null} placeholder="请选择等级">
                    <Radio value={1001}>普通员工</Radio>
                    <Radio value={1002}>上级</Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item
                name="password"
                label="登录密码"
                rules={[{
                    required: !state.form.id,
                    validator: (rule, value) => {
                        if (!state.form.id) {
                            return new ValidationRules({
                                prop: 'password',
                                message: '密码',
                                type: 'password',
                                limit: 12,
                                inputControll: true,
                                value
                            }).validate(rule, value)
                        }
                        return Promise.resolve()
                    },
                }]}
            >
                <Input.Password
                    autoComplete="off"
                    placeholder={setting.message.password}
                />
            </Form.Item>
            <Form.Item
                name="reptpassword"
                label="重复密码"
                rules={[{
                    required: !state.form.id,
                    validator: (rule, value) => {
                        if (!state.form.id) {
                            return new ValidationRules({
                                prop: 'password',
                                message: '密码',
                                type: 'password',
                                limit: 12,
                                inputControll: true,
                                value
                            }).validate(rule, value)
                        }
                        return Promise.resolve()
                    },
                }]}
            >
                <Input.Password
                    placeholder={setting.message.password}
                />
            </Form.Item>
            <Form.Item style={{ marginTop: 24 }} wrapperCol={{ push: 4 }}>
                <Button type="primary" className="mr10" loading={loading} htmlType="submit">
                    保存
                </Button>
                <Button onClick={() => props.removeTabs(`/userCenter/${state.form.id ? 'edit' : 'add'}`)} loading={loading}>
                    取消
                </Button>
            </Form.Item>
        </Form>
    </div>
}
export default React.memo(AddOrEditUser);